/**
 * All-right reserved by gglu\lqz\qq 2010-2020
 */
package com.injury.hunan.dao.test;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;


/**
 * 请写上此类的主要功能
 * @author gglu
 * @version 2008年7月21日 上午8:42:31
 * @surpportjdk 1.5+
 * 
 */
public class AbstractDaoBaseTestCase {

	protected static ClassPathXmlApplicationContext appcontext;
	
	/**
	 * 初始化spring上下文.
	 */
	@BeforeClass
	public static void initContext(){
		
		appcontext = new ClassPathXmlApplicationContext("/dao.xml");
		
		appcontext.getBean("sessionFactory");
	}
	
	@AfterClass
	public static void afterAllTests(){
		if(null != appcontext && appcontext.isActive()){
			appcontext.destroy();
		}
		appcontext = null;
		
	}
	
	/**
	 * 在事务性环境下执行.
	 */
	public <T> T doInTx(DaoCallback<T> cb){
		
		T ret = null;
		
		PlatformTransactionManager txmanager = appcontext.getBean("transactionManager",PlatformTransactionManager.class);
		
		TransactionStatus tx = txmanager.getTransaction(buildTransactionDefinition());
		
		try {
			ret = cb.execute(tx);
			txmanager.commit(tx);
		} catch (RuntimeException e) {
			e.printStackTrace();
			tx.setRollbackOnly();
			txmanager.rollback(tx);
			throw e;
		}
		
		return ret;
	}
	
	/**
	 * 还没想好是否有必要性.
	 */
	public <T> T doWithoutTX(DaoCallback<T> cb){
		
		return cb.execute(null);
	}
	
	/**
	 * 
	 */
	protected TransactionDefinition buildTransactionDefinition() {
		TransactionDefinition txdef = new DefaultTransactionAttribute();
		
		
		return txdef;
	}

	protected interface DaoCallback<T> {
		
		/**
		 * 可判断tx是否为null，来确认当前执行环境是否有事务.
		 */
		T execute(TransactionStatus tx);

	}
	
	
	@Test
	public void testInit(){
		
	}
}
